//
//  PlanRecommendHeadView.m
//  WanCaiC8
//
//  Created by tangang on 2018/3/23.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "PlanRecommendHeadView.h"
#import "HomePageVM.h"
#import "LotteryNumCell.h"
#import "AdvertisingView.h"
@interface PlanRecommendHeadView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic ,strong) UICollectionView  *collectionView;

@property (nonatomic ,strong) UICollectionView  *bottomCollectionView;

@property (nonatomic ,strong) AdvertisingView  *oneAdvertisingView;


@end

@implementation PlanRecommendHeadView{
    
    
    
    QXLable     *labNum;
    QXLable     *labTime;
    QXLable     *labTimeContent;
    UIView      *line;
    dispatch_source_t _timer;
    Home_LotteryModel *lotteryModel;
    UIImageView *imageArrow;
}



- (instancetype)initWithType:(LotteryNumType)type{
    if (self=[super init]) {
        
        [self setFrame:CGRectMake(0, 0, SCREEN_WIDTH, real_size(115))];
        labNum=[[QXLable alloc]init];
        [self addSubview:labNum];
        [labNum mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(self).with.offset(13);
        }];
        
        labTime=[[QXLable alloc]init];
        labTime.textAlignment=NSTextAlignmentRight;
        labTime.numberOfLines=0;
        [self addSubview:labTime];
        [labTime sizeToFit];
        
        [labTime mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self).with.offset(-13);
            make.centerY.equalTo(labNum);
        }];
        
        labTimeContent=[[QXLable alloc]init];
        labTimeContent.textColor=NAVCOLOR;
        labTimeContent.font=[UIFont systemFontOfSize:18];
        labTimeContent.textAlignment=NSTextAlignmentRight;
        labTimeContent.numberOfLines=0;
        [self addSubview:labTimeContent];
        [labTimeContent mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self).with.offset(-13);
            make.top.equalTo(labTime.mas_bottom).with.offset(13);
            make.height.mas_equalTo(@(real_size(18)));
        }];
        
        [self addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(labNum);
            make.right.equalTo(self);
            make.centerY.equalTo(labTimeContent);
            make.height.mas_equalTo(@(real_size(27)));
        }];
        
        
        
        line=[[UIView alloc]init];
        line.backgroundColor=DEFAULTBGCOLOR;
        [self addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(self.collectionView.mas_bottom).with.offset(13);
            make.height.mas_equalTo(@.7);
        }];
        
        
        
        
        [self addSubview:self.oneAdvertisingView];
        [self.oneAdvertisingView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self).offset(-10);
            make.left.equalTo(self).offset(10);
            make.top.equalTo(line);
            make.bottom.equalTo(self);
        }];
        
        
        self.lookNew =[[UIButton alloc] init];
        self.lookNew.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        [self.lookNew setTitleColor:NAVCOLOR forState:UIControlStateNormal];
        [self.lookNew.titleLabel setFont:[UIFont systemFontOfSize:13]];
        //        if (!_isNew) {
        //        [lookNew setTitleColor:NAVCOLOR forState:UIControlStateNormal];
        //        //        } else {
        //        //            [lookNew setTitleColor:DEFAULTTEXTGDARKRAYCOLOR forState:UIControlStateNormal];
        //        //        }
        
        
        
        [self.lookNew addTarget:self action:@selector(onclickNew) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.lookNew];
        [self.lookNew mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self);
            make.left.equalTo(labNum);
            make.top.equalTo(line);
            make.bottom.equalTo(self);
        }];
        
        imageArrow=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow_right"]];
        [self addSubview:imageArrow];
        [imageArrow mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.lookNew);
            make.right.equalTo(self).with.offset(-10);
            make.size.mas_equalTo(imageArrow.image.size);
        }];
      
    }
    return self;
}


- (void)setIsNew:(BOOL)isNew{
    
    _isNew = isNew;
    self.lookNew.hidden=isNew;
    line.hidden=isNew;
    imageArrow.hidden=isNew;
}

- (void)onclickNew{
    if (self.lookNewBlock) {
        self.lookNewBlock(lotteryModel.CurrentIssue);
    }
}

- (void)setLType:(NSString *)lType{
    
    
    if (lType == nil) {
        return;
    }

    _lType=lType;
    WS(weakSelf);
    //网络请求
    [[HomePageVM manage] getLotteryInfoWithId:lType Success:^(id returnValue) {
        [weakSelf updateUI:returnValue];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

- (void)updateUI:(Home_LotteryModel *)model{
    lotteryModel=model;
    
    
    
        labNum.text=[NSString stringWithFormat:@"%@期",lotteryModel.Issue];
        labTime.text=[NSString stringWithFormat:@"距%@期截止",model.CurrentIssue];
        labTimeContent.text=[NSString stringWithFormat:@"%@",model.OpenTime];
//        [lookNew setTitle:[NSString stringWithFormat:@"查看%@期%@计划",lotteryModel.CurrentIssue,lotteryModel.LTypeName] forState:UIControlStateNormal];
//    
    if (!_isNew) {
        [self.lookNew setTitle:[NSString stringWithFormat:@"查看%@期%@计划",lotteryModel.CurrentIssue,lotteryModel.LTypeName] forState:UIControlStateNormal];
    }else{
        
    }
    
    
    [self startTimer];
    [self.collectionView reloadData];
}

- (NSMutableAttributedString *)topStr:(NSString *)topStr andDownStr:(NSString *)downStr andTextAlianment:(NSTextAlignment)alianment{
    NSMutableAttributedString *attStr=[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@\n%@",topStr,downStr]];
    [attStr addAttribute:NSForegroundColorAttributeName value:NAVCOLOR range:NSMakeRange(topStr.length, attStr.length-topStr.length)];
    [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:NSMakeRange(topStr.length, attStr.length-topStr.length)];
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.lineSpacing = 12; //设置行间距
    paraStyle.alignment=alianment;
    [attStr addAttribute:NSParagraphStyleAttributeName value:paraStyle range:NSMakeRange(0, attStr.length)];
    return attStr;
}

#pragma mark -- 启动定时器
- (void)startTimer{
    WS(weakSelf);
    [self cancleTimer];
    [self performSelector:@selector(updateData) withObject:nil afterDelay:15];
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
      
        
        if (![lotteryModel.OpenTime isEqualToString:@"正在开奖"]) {
            NSArray *timeArr=[lotteryModel.OpenTime componentsSeparatedByString:@":"];
            int hour=[timeArr[0] intValue];
            int minutes=[timeArr[1] intValue];
            int second=[timeArr[2] intValue];
            if (second>0) {
                second-=1;
                lotteryModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
            }else if (minutes>0){
                minutes-=1;
                second=59;
                lotteryModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
            }else if (hour>0){
                hour-=1;
                minutes=59;
                second=59;
                lotteryModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
            }else{
                [self cancleTimer];
                lotteryModel.OpenTime=@"正在开奖";
                
            
            }
            
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            labTimeContent.text=[NSString stringWithFormat:@"%@",lotteryModel.OpenTime];
        });
        
    });
    dispatch_resume(_timer);
}

- (void)updateData{
    
    self.lType=self.lType;
    

}

- (void)cancleTimer{
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
}

- (void)setAdvertisingModel:(AdvertisingModel *)advertisingModel{
    _advertisingModel=advertisingModel;
    
    if ([advertisingModel.Title containsString:@"【"]) {
        [self.lookNew setAttributedTitle: [NSAttributedString tg_imageTextWithTitle:advertisingModel.Title] forState:UIControlStateNormal];
 
    } else {
        [self.lookNew setTitle:advertisingModel.Title forState:UIControlStateNormal];
        [self.lookNew setTitleColor:DEFAULTTEXTGDARKRAYCOLOR forState:UIControlStateNormal];
    }
    [self.lookNew addTarget:self action:@selector(onclickAdVertising) forControlEvents:UIControlEventTouchUpInside];
    
    if (!_isNew) {
        [self.lookNew setTitle:[NSString stringWithFormat:@"查看%@期%@计划",lotteryModel.CurrentIssue,lotteryModel.LTypeName] forState:UIControlStateNormal];
    }else{
        
    }

//    UIView *line=[[UIView alloc]init];
//    [self addSubview:line];
//    [line mas_makeConstraints:^(MASConstraintMaker *make) {
//
//    }];
    self.lookNew.hidden=NO;
    line.hidden=NO;
}

- (void)onclickAdVertising{
    if (self.advertisingModel.TransferUrl.length<1) {
        return;
    }
    
    if ([self.advertisingModel.Title containsString:@"】"]) {
        
        UIPasteboard *copy = [UIPasteboard generalPasteboard];
        NSRange startRange = [self.advertisingModel.Title rangeOfString:@"【"];
        NSRange endRange = [self.advertisingModel.Title rangeOfString:@"】"];
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
        NSString *result = [self.advertisingModel.Title substringWithRange:range];
        
        [copy setString:result];
        
        [SVProgressHUD showSuccessWithStatus:@"复制成功"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString: @"weixin://"]];
        });

    }else{
        
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString: self.advertisingModel.TransferUrl]];
        
    }
  
}


#pragma mark - collectionView代理函数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    LotteryNumType type=[[BaseVM manage]getType:[lotteryModel.LType integerValue]];
    if ([lotteryModel.LType integerValue]==65) {
        return lotteryModel.PCArr.count;
    }else if (type==LotteryNumTypeLottery||type==LotteryNumTypeChromosphere||type==LotteryNumTypeSevenLecai){
        return lotteryModel.LotteryArr.count;
    }else if (type==LotteryNumTypeBrings){
        return lotteryModel.BringsArr.count;
    }
    return lotteryModel.numArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LotteryNumCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"LotteryNumCell" forIndexPath:indexPath];
    LotteryNumType type=[[BaseVM manage]getType:[lotteryModel.LType integerValue]];
    if ([lotteryModel.LType integerValue]==65) {
        [cell setTitle:lotteryModel.PCArr[indexPath.row] andType:type];
    }else if (type==LotteryNumTypeLottery||type==LotteryNumTypeChromosphere||type==LotteryNumTypeSevenLecai){
        [cell setTopTitle:lotteryModel.LotteryArr[indexPath.row] andType:type andTitleColor:NAVCOLOR];
    }else if (type==LotteryNumTypeBrings){
        [cell setTopTitle:lotteryModel.BringsArr[indexPath.row] andType:type andTitleColor:NAVCOLOR];
    }
    else{
        [cell setTopTitle:lotteryModel.numArr[indexPath.row] andType:type andTitleColor:NAVCOLOR];
    }
    if ((type==LotteryNumTypeChromosphere||type==LotteryNumTypeSevenLecai)&&(indexPath.row==lotteryModel.LotteryArr.count-1)) {
        [cell setTopTitle:lotteryModel.LotteryArr[indexPath.row] andType:type andTitleColor:DEFAULTTEXTBLUECOLOR];
    }else if (type==LotteryNumTypeBrings&&(indexPath.row==lotteryModel.LotteryArr.count-1)){
        [cell setTopTitle:lotteryModel.BringsArr[indexPath.row] andType:type andTitleColor:DEFAULTTEXTBLUECOLOR];
    }
    else if ((type==LotteryNumTypeChromosphere||type==LotteryNumTypeSevenLecai)&&(indexPath.row==lotteryModel.LotteryArr.count-2)){
        [cell setTopTitle:lotteryModel.LotteryArr[indexPath.row] andType:type andTitleColor:DEFAULTTEXTBLACKCOLOR];
    }else if ((type==LotteryNumTypeBrings)&&(indexPath.row==lotteryModel.LotteryArr.count-2)){
        [cell setTopTitle:lotteryModel.BringsArr[indexPath.row] andType:type andTitleColor:DEFAULTTEXTBLUECOLOR];
    }else if ((type==LotteryNumTypeBrings)&&(indexPath.row==lotteryModel.LotteryArr.count-3)){
        [cell setTopTitle:lotteryModel.BringsArr[indexPath.row] andType:type andTitleColor:DEFAULTTEXTBLACKCOLOR];
    }
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    LotteryNumType type=[[BaseVM manage]getType:[lotteryModel.LType integerValue]];
    NSString *str;
    if (type==LotteryNumTypeLottery||type==LotteryNumTypeChromosphere||type==LotteryNumTypeSevenLecai) {
        str=lotteryModel.LotteryArr[indexPath.row];
    }else if (type==LotteryNumTypeBrings){
        str=lotteryModel.BringsArr[indexPath.row];
    }
    else{
        str=lotteryModel.numArr[indexPath.row];
    }
    
    if ([str isEqualToString:@"+"]) {
        return CGSizeMake(real_size(15), real_size(27));
    }
    
    if (type==LotteryNumTypeLottery){
        return CGSizeMake(real_size(27), real_size(27));
    }
    if (str.length>1) {
        return CGSizeMake(real_size(27), real_size(27));
    }
    
    return CGSizeMake(real_size(18), real_size(27));
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

#pragma mark -- 懒加载
- (UICollectionView *)collectionView{
    if (_collectionView==nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setItemSize:CGSizeMake(real_size(27), real_size(27))];
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        layout.minimumInteritemSpacing = 3.0;
        layout.minimumLineSpacing = 0.0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor=[UIColor clearColor];
        _collectionView.showsVerticalScrollIndicator=NO;
        [_collectionView registerClass:[LotteryNumCell class] forCellWithReuseIdentifier:@"LotteryNumCell"];
    }
    return _collectionView;
}

- (UICollectionView *)bottomCollectionView{
    if (_bottomCollectionView==nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setItemSize:CGSizeMake(25, 25)];
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        layout.minimumInteritemSpacing = 0.0;
        layout.minimumLineSpacing = 0.0;
        _bottomCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _bottomCollectionView.delegate = self;
        _bottomCollectionView.dataSource = self;
        _bottomCollectionView.backgroundColor=[UIColor whiteColor];
        _bottomCollectionView.showsVerticalScrollIndicator=NO;
        [_bottomCollectionView registerClass:[LotteryNumCell class] forCellWithReuseIdentifier:@"LotteryNumCell"];
    }
    return _bottomCollectionView;
}


-(void)setModelArr:(NSMutableArray<AdvertisingModel *> *)modelArr{
    _modelArr = modelArr;
    self.isNew = YES;
    
    self.oneAdvertisingView.dataArr = modelArr;
    
    [self.oneAdvertisingView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(modelArr.count*40);
    }];
    
}

-(void)setModelArr:(NSMutableArray *)modelArr AndRowCount:(NSInteger)rowCount{
    _modelArr = modelArr;
     self.isNew = YES;
    self.oneAdvertisingView.dataArr = modelArr;
    self.oneAdvertisingView.changeHeight(rowCount*40);
//        [self.oneAdvertisingView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.mas_equalTo(rowCount*40);
//        }];
    
}



- (AdvertisingView *)oneAdvertisingView{
    if (!_oneAdvertisingView) {
        WS(weakSelf);
        _oneAdvertisingView =[[AdvertisingView alloc]init];
        self.oneAdvertisingView.changeHeight = ^(float height) {
            [weakSelf.oneAdvertisingView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(@(height));
            }];
        };
    }
    return _oneAdvertisingView;
}

- (void)dealloc
{
    NSLog(@"planRecommendheadView 。销毁");

}

@end
